看一百遍美女,美女也不一定是你的。但你刷一百遍算法,知识就是你的了~~
谁能九层台,不用累土起!
题目地址
题目 设计实现双端队列。
你的实现需要支持以下操作:
MyCircularDeque(k):构造函数,双端队列的大小为k。
insertFront():将一个元素添加到双端队列头部。 如果操作成功返回true。
insertLast():将一个元素添加到双端队列尾部。如果操作成功返回true。
deleteFront():从双端队列头部删除一个元素。 如果操作成功返回true。
deleteLast():从双端队列尾部删除一个元素。如果操作成功返回true。
getFront():从双端队列头部获得一个元素。如果双端队列为空,返回-1。
getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回-1。
isEmpty():检查双端队列是否为空。
isFull():检查双端队列是否满了。
示例:
1 2 3 4 5 6 7 8 9 10 MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3 circularDeque.insertLast(1); // 返回 true circularDeque.insertLast(2); // 返回 true circularDeque.insertFront(3); // 返回 true circularDeque.insertFront(4); // 已经满了,返回 false circularDeque.getRear(); // 返回 2 circularDeque.isFull(); // 返回 true circularDeque.deleteLast(); // 返回 true circularDeque.insertFront(4); // 返回 true circularDeque.getFront(); // 返回 4
解题思路
我们定义一个数组,如果数组的长度与要求的队列长度长度相同则isFull
如果数组的长度为0,则满足isEmpty
insertLast其实就是往数组中第一项插入元素
insertLast其实就是往数组中push元素
deleteFront其实就是移除数组的第一项元素
deleteLast其实就是移除数组的最后一项元素
getRear获取最后一项也就是获取数组的第length-1项
getFront获取数组第0项
提示:
所有值的范围为[1, 1000]
操作次数的范围为[1, 1000]
请不要使用内置的双端队列库。
解题代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 var MyCircularDeque = function (k ) { this .maxLen = k this .arr = [] }; MyCircularDeque.prototype.insertFront = function (value ) { if (this .isFull()) return false this .arr = [value,...this.arr] return true }; MyCircularDeque.prototype.insertLast = function (value ) { if (this .isFull()) return false this .arr.push(value) return true }; MyCircularDeque.prototype.deleteFront = function ( ) { if (this .isEmpty()) return false let [a,...args] = this .arr this .arr = [...args] return true }; MyCircularDeque.prototype.deleteLast = function ( ) { if (this .isEmpty()) return false this .arr = this .arr.slice(0 ,this .arr.length-1 ) return true }; MyCircularDeque.prototype.getFront = function ( ) { if (this .isEmpty()) return -1 return this .arr[0 ] }; MyCircularDeque.prototype.getRear = function ( ) { if (!this .arr.length) return -1 return this .arr[this .arr.length-1 ] }; MyCircularDeque.prototype.isEmpty = function ( ) { return this .arr.length == 0 }; MyCircularDeque.prototype.isFull = function ( ) { return this .arr.length == this .maxLen };
如有任何问题或建议,欢迎留言讨论!